let websocket = new WebSocket("ws://" + location.host + "/message");
//连接成功建⽴的回调⽅法
websocket.onopen = function () {
    console.log("open");
}

//连接发⽣错误的回调⽅法
websocket.onerror = function () {
    console.log("error");
};
//监听窗⼝关闭事件，当窗⼝关闭时，主动去关闭websocket连接，防⽌连接还没断开就关闭窗⼝，server端会抛异常。
window.onbeforeunload = function () {
    websocket.close();
}

websocket.onmessage = function (event) {
    console.log('[onmessage] ' + event.data);
    let resp = JSON.parse(event.data);
    if (resp.type == 'message') {
        // 处理消息响应
        handlerMessage(resp);
    }
    else if (resp.type == 'addFriendRequest') {
        // 处理添加好友请求
        handlerAddFriend(resp);
    } else if (resp.type == 'acceptFriend') {
        // 处理接受好友响应
        handlerAcceptFriend(resp);
    }
}
//连接关闭的回调⽅法
websocket.onclose = function () {
    console.log("close");
}


function initSwitchTab() {
    let tabSession = document.querySelector('.tab-session');
    let tabFriend = document.querySelector('.tab-friend');
    let lists = document.querySelectorAll('.list');

    tabSession.onclick = function () {
        tabSession.style.backgroundImage = 'url(img/对话.png)';
        tabFriend.style.backgroundImage = 'url(img/用户2.png)';
        lists[0].classList = 'list';
        lists[1].classList = 'list hide';
    }

    tabFriend.onclick = function () {
        tabSession.style.backgroundImage = 'url(img/对话2.png)';
        tabFriend.style.backgroundImage = 'url(img/用户.png)';
        lists[0].classList = 'list hide';
        lists[1].classList = 'list';
    }
}
function getUserInfo() {
    $.ajax({
        type: 'get',
        url: '/user/getUserInfo',
        success: function (result) {
            let userDiv = document.querySelector('.user');
            userDiv.innerHTML += '<span>' + result.data.nickname + ' (' + result.data.username + ')</span>';
            // userDiv.innerHTML += '<button class=showUserInfo></button>';
            userDiv.setAttribute('userId', result.data.userId);
            // let showButton = document.querySelector('.showUserInfo');
            // showButton.onclick = function () {
            //     $('.main').removeClass('main').addClass('main-userInfo');
            //     $('.left').removeClass('left').addClass('left-unactivated');
            //     $('.right').removeClass('right').addClass('right-unactivated');
            //     html = '';
            //     html += '<div class="profile-container">';
            //     html += '<img src="https://via.placeholder.com/100" alt="头像" class="profile-avatar">';
            //     html += '<div class="profile-name">张三</div>';
            //     html += '<div class="profile-nickname">@zhangsan</div>';
            //     html += '</div>';
            //     $('.main-userInfo').html(html);
            // }
        },
        error: function () {
            alert("获取当前⽤⼾信息失败!");
        }
    });
}


function getFriendList() {
    $.ajax({
        type: 'get',
        url: '/friend/getFriendList',
        success: function (result) {
            console.log(result);
            let friendList = document.querySelector('#friend-list');
            friendList.innerHTML = '';
            if (result.data == null) return;
            for (var friend of result.data) {
                let li = document.createElement('li');
                li.setAttribute('friend-id', friend.friendId);
                //后端处理,直接显示friendName即可
                li.innerHTML = '<h4>' + friend.friendName + '<h4>';
                friendList.appendChild(li);
                li.onclick = function () {
                    clickFriend(friend);
                }
            }
        },
        error: function () {
            alert('获取好友列表失败!');
        }
    });
}

function getSessionList() {
    $.ajax({
        type: 'get',
        url: '/messageSession/getMessageSessionList',
        success: function (result) {
            let sessionList = document.querySelector('#session-list');
            sessionList.innerHtml = '';
            console.log(result.data);
            let count = 0;
            for (var session of result.data) {
                if (session.lastMessage == null) continue;
                if (session.lastMessage.length > 10) {
                    session.lastMessage = session.lastMessage.substring(0, 10) + '...';
                }
                let li = document.createElement('li');
                li.setAttribute('message-session-id', session.sessionId);
                li.innerHTML = '<h3 class=sessionName>' + session.friends[0].friendNickname + '</h3>' + '<p>' + (session.lastMessage || '') + '<p>';
                sessionList.appendChild(li);
                li.onclick = function () {
                    clickSession(li, session.friends[0].friendId);
                }
                if (localStorage.getItem('clickFirstSession') != null && count == 0) {
                    clickSession(li, session.friends[0].friendId);
                    localStorage.removeItem('clickFirstSession');
                    count++;
                }
            }
        }, error: function () {
            alert('会话列表列表获取失败!');
        }
    });
}

function clickSession(currentSessionLi, friendId) {
    var sessionLis = document.querySelectorAll('#session-list>li');
    activeSession(sessionLis, currentSessionLi);
    var sessionId = currentSessionLi.getAttribute('message-session-id');
    getHistoryMessage(sessionId, friendId);
}

function activeSession(sessionLis, activeSessionLi) {
    for (var sessionLi of sessionLis) {
        if (sessionLi == activeSessionLi) {
            sessionLi.className = 'selected';
        } else {
            sessionLi.className = '';
        }
    }
}

function getHistoryMessage(sessionId, friendId) {
    console.log('获取历史信息: ' + sessionId);
    let titleDiv = document.querySelector('.right>.title');
    let messageShowDiv = document.querySelector('.message-show');
    titleDiv.innerHTML = '';
    messageShowDiv.innerHTML = '';
    let selectedH3 = document.querySelector('#session-list>.selected>h3');
    if (selectedH3) {
        titleDiv.innerHTML += '<span class=friendNickname>' + selectedH3.innerHTML.trim() + '</span>';
        titleDiv.innerHTML += '<button class=changeNickname></button>';
        let button = document.querySelector('.changeNickname');
        button.onclick = function () {
            //弹框输入
            $('.update-unactivated').removeClass('update-unactivated').addClass('update');
            $('.message-input').removeClass('message-input').addClass('message-input-unactivated');
            $('.ctrl').removeClass('ctrl').addClass('ctrl-unactivated');
            let updateDiv = document.querySelector('.update');
            updateDiv.innerHTML = '';
            updateDiv.innerHTML += '<span>输入想修改的昵称:<span>';
            //input改text
            updateDiv.innerHTML += '<input class=updateNickname></input>';
            updateDiv.innerHTML += '<button class=submit>修改</button>';
            updateDiv.innerHTML += '<button class=cancel>取消</button>';

            let submitButton = document.querySelector('.submit');
            submitButton.onclick = function () {
                let friendNickname = document.querySelector('.updateNickname').value;
                if (friendNickname.length > 15) {
                    alert('昵称太长了哦!');
                    return;
                }
                $.ajax({
                    type: 'post',
                    url: '/friend/updateFriendNickname',
                    data: {
                        friendId: friendId,
                        friendNickname: friendNickname,
                    },
                    success: function (result) {
                        alert('修改昵称成功!');
                        location.href = '/client.html';
                        localStorage.setItem('clickFirstSession', 1);
                    }
                });
            }
            let cancelButton = document.querySelector('.cancel');
            cancelButton.onclick = function () {
                $('.update').removeClass('update').addClass('update-unactivated');
                $('.message-input-unactivated').removeClass('message-input-unactivated').addClass('message-input');
                $('.ctrl-unactivated').removeClass('ctrl-unactivated').addClass('ctrl');
            }
        }
    }
    if (!selectedH3) {
        return;
    }
    $.ajax({
        type: 'get',
        url: '/message/getMessageList?sessionId=' + sessionId,
        success: function (result) {
            for (var message of result.data) {
                addMessage(messageShowDiv, message);
            }
            scrollBottom(messageShowDiv);
        },
        error: function () {
            alert('获取历史消息失败!');
        }
    });
}


function addMessage(messageShowDiv, message) {
    let selfUserId = document.querySelector('.user').getAttribute('userId');
    let messageDiv = document.createElement('div');
    if (message.fromId != selfUserId) {
        messageDiv.className = 'message message-left';
    } else {
        messageDiv.className = 'message message-right';
    }
    messageDiv.innerHTML = '<div class="box">' + '<h4>' + message.fromName + ' |' + message.postTime + '</h4>'
        + '<p>' + message.content + '</p>' + '</div>';
    messageShowDiv.appendChild(messageDiv);
}

function scrollBottom(elem) {
    const clientHeight = elem.offsetHeight; // 容器⾼度
    const scrollHeight = elem.scrollHeight; // 内容总⾼度
    // 第⼀个参数是⽔平⽅向滚动的距离, 第⼆个参数是垂直⽅向滚动的距离.
    elem.scrollTo(0, scrollHeight - clientHeight);
}

function clickFriend(friend) {
    let sessionLi = findSessionByName(friend.friendName);
    let sessionList = document.querySelector('#session-list');
    if (sessionLi) {
        sessionList.insertBefore(sessionLi, sessionList.children[0]);
        sessionLi.click();
    } else {
        sessionLi = document.createElement('li');
        sessionLi.innerHTML = '<h3>' + friend.friendName + '</h3>' + '<p></p>';
        sessionList.insertBefore(sessionLi, sessionList.children[0]);
        sessionLi.onclick = function () {
            clickSession(sessionLi);
        }
        sessionLi.click();
        createSession(friend.friendId, sessionLi);
    }

    let tabSession = document.querySelector('.tab-session');
    tabSession.click();

}

function findSessionByName(name) {
    let sessions = document.querySelectorAll('#session-list>li');
    for (let li of sessions) {
        let h3 = li.querySelector('h3');
        if (name == h3.innerHTML) {
            return li;
        }
    }
    return null;
}

function createSession(friendId, sessionLi) {
    $.ajax({
        type: 'post',
        url: '/messageSession/addMessageSession?toUserId=' + friendId,
        success: function (result) {
            console.log('创建会话成功!' + result.data.sessionId);
            sessionLi.setAttribute('message-session-id', result.data.sessionId);
        },
        error: function () {
            alert("创建会话失败!");
        }
    });
}

function initSendButton() {
    // 1. 获取到发送按钮 和 消息输入框
    let sendButton = document.querySelector('.right .ctrl button');
    let messageInput = document.querySelector('.right .message-input');
    // 2. 给发送按钮注册一个点击事件
    sendButton.onclick = function () {
        // a) 先针对输入框的内容做个简单判定. 比如输入框内容为空, 则啥都不干
        if (!messageInput.value) {
            // value 的值是 null 或者 '' 都会触发这个条件
            return;
        }
        // b) 获取当前选中的 li 标签的 sessionId
        let selectedLi = document.querySelector('#session-list .selected');
        if (selectedLi == null) {
            // 当前没有 li 标签被选中. 
            return;
        }
        let sessionId = selectedLi.getAttribute('message-session-id');
        // c) 构造 json 数据
        let req = {
            type: 'message',
            sessionId: sessionId,
            content: messageInput.value
        };
        req = JSON.stringify(req);
        console.log("[websocket] send: " + req);
        // d) 通过 websocket 发送消息
        websocket.send(req);
        // e) 发送完成之后, 清空之前的输入框
        messageInput.value = '';
    }
}

function handlerMessage(resp) {
    // 1. 根据 resp 中的 sessionId, 找到 session 列表中的元素. 如果不存在, 则创建⼀个新会话
    let sessionListUL = document.querySelector('#session-list');
    let curSessionLi = findSessionById(resp.sessionId);
    if (curSessionLi == null) {
        // 如果为空, 则创建出⼀个新的会话来.
        curSessionLi = document.createElement('li');
        curSessionLi.setAttribute('message-session-id', resp.sessionId);
        curSessionLi.innerHTML = '<h3>' + resp.fromName + '</h3>'
            + '<p></p>';
        curSessionLi.onclick = function () {
            clickSession(curSessionLi);
        }
    }
    // 2. 把新消息显⽰在会话预览栏中.
    let p = curSessionLi.querySelector('p');
    p.innerHTML = resp.content;
    if (p.innerHTML.length > 10) {
        // 如果消息太⻓了, 就在预览窗⼝中截断.
        p.innerHTML = p.innerHTML.substring(0, 10) + '...';
    }
    // 3. 把会话调整到会话列表最上⽅.
    sessionListUL.insertBefore(curSessionLi, sessionListUL.children[0]);
    // 如果当前会话已经选中, 则
    if (curSessionLi.className == 'selected') {
        // 4. 在消息列表中显⽰新的消息
        let messageShowDiv = document.querySelector('.message-show');
        addMessage(messageShowDiv, resp);
        // 5. 调整滚动条位置.
        scrollBottom(messageShowDiv)
    }
    // [下列功能暂时不做, 留作同学们⾃⾏扩展]
    // 6. 还可以在会话窗⼝上提⽰ 红⾊ 的数字, 表⽰未读消息.
    // 7. 播放消息提⽰⾳效.
}
function handlerAddFriend(resp) {
    addFriendRequest(resp.fromUserId, resp.fromUserName, resp.reason);
}
function handlerAcceptFriend(resp) {
    // 1. 刷新好友列表
    getFriendList();
    // 2. 弹框提⽰
    alert(resp.fromUserName + ' 已经通过你的好友申请!');
}

function findSessionById(targetSessionId) {
    let sessionLis = document.querySelectorAll('#session-list>li');
    for (let sessionLi of sessionLis) {
        let sessionId = sessionLi.getAttribute('message-session-id');
        if (sessionId == targetSessionId) {
            return sessionLi;
        }
    }
    // 正常情况下不会触发这⾥的 return null, 服务器返回的会话是⼀定能找到的.
    return null;
}
function initFindFriend() {
    let search = document.querySelector('.search');
    let input = document.querySelector('.search>input');
    let button = document.querySelector('.search>button');
    button.onclick = function () {
        $.ajax({
            type: 'get',
            url: '/friend/findFriend?friendName=' + encodeURIComponent(input.value.trim()),
            success: function (result) {
                console.log(result.data);
                let titleDiv = document.querySelector('.title');
                titleDiv.innerHTML = '查找结果';
                let messageShowDiv = document.querySelector('.message-show');
                messageShowDiv.innerHTML = '';
                for (let friend of result.data) {
                    let itemDiv = document.createElement('div');
                    itemDiv.className = 'message';
                    let span = document.createElement('span');
                    span.innerHTML = friend.friendName;
                    span.setAttribute('friend-id', friend.friendId);
                    let input = document.createElement('input');
                    input.type = 'text';
                    input.placeholder = '添加好友理由';
                    let button = document.createElement('button');
                    button.innerHTML = '添加';
                    button.onclick = function () {
                        sendAddFriend(friend.friendId, input.value);
                    }
                    itemDiv.appendChild(span);
                    itemDiv.appendChild(input);
                    itemDiv.appendChild(button);
                    messageShowDiv.appendChild(itemDiv);
                }
            },
            error: function () {
                alert('查找好友失败!name=' + input.value.trim());
            }
        });
    }
}
function sendAddFriend(friendId, reason) {
    $.ajax({
        type: 'get',
        url: '/friend/addFriend?friendId=' + friendId + '&reason=' + encodeURIComponent(reason),
        success: function (result) {
            alert('添加好友的请求已发送!');
        },
        error: function () {
            alert('添加好友失败!');
        }

    });
}
function getAddFriendRequest() {
    $.ajax({
        type: 'get',
        url: '/friend/getFriendRequest',
        success: function (result) {
            for (let item of result.data) {
                addFriendRequest(item.fromUserId, item.fromUserName,
                    item.reason);
            }
        },
        error: function () {
            alert('加载添加好友请求失败!');
        }
    });
}
function addFriendRequest(fromUserId, fromUserName, reason) {
    let sessionList = document.querySelector('#session-list');
    let li = document.createElement('li');
    li.setAttribute('from-user-id', fromUserId);
    li.style = 'height: 100px';
    let h3 = document.createElement('h3');
    h3.innerHTML = fromUserName;
    let p = document.createElement('p');
    p.innerHTML = '添加理由: ' + reason;
    let rowDiv = document.createElement('div');
    rowDiv.className = 'row';
    let buttonAccept = document.createElement('button');
    buttonAccept.innerHTML = '接受';
    buttonAccept.onclick = function () {
        $.ajax({
            type: 'get',
            url: '/friend/acceptFriend?friendId=' + fromUserId,
            success: function () {
                alert('通过' + fromUserName + "的好友申请 处理成功!");
                getFriendList();
                sessionList.removeChild(li);
            },
            error: function () {
                alert('通过' + fromUserName + "的好友申请 处理失败!");
            }
        });
    }
    let buttonReject = document.createElement('button');
    buttonReject.innerHTML = '拒绝';
    buttonReject.onclick = function () {
        $.ajax({
            type: 'get',
            url: '/friend/rejectFriend?friendId=' + fromUserId,
            success: function () {
                alert('拒绝' + fromUserName + "的好友申请 处理成功!");
                sessionList.removeChild(li);
            },
            error: function () {
                alert('拒绝' + fromUserName + "的好友申请 处理失败!");
            }
        });
    }
    li.appendChild(h3);
    li.appendChild(p);
    rowDiv.appendChild(buttonAccept);
    rowDiv.appendChild(buttonReject);
    li.appendChild(rowDiv);
    sessionList.insertBefore(li, sessionList.children[0]);
}
initSwitchTab();
getUserInfo();
getFriendList();
getSessionList();
initSendButton();
initFindFriend();
getAddFriendRequest();

